/*
** main.c for lemipc in /home/seth/lemipc
** 
** Made by kevin lansel
** Login   <lansel_k@epitech.net>
** 
** Started on  Mon Mar 25 16:26:14 2013 kevin lansel
** Last update Wed Mar 27 10:04:35 2013 kevin lansel
*/

#include	"lemipc.h"


char	*xget_current_dir_name()
{
  char	*pwd;

  if ((pwd = get_current_dir_name()) == NULL)
    {
      perror(get_current_dir_name());
      exit(EXIT_FAILURE);
    }
  return (pwd);
}

key_t	xftok()
{
  key_t	key;

  if ((key = ftok(get_current_dir_name(), 0)) == -1)
    {
      perror("ftok");
      exit(EXIT_FAILURE);
    }
  return (key);
}

void	xsemctl(int sem_id, int semnum, int cmd, int val)
{
  if (semctl(sem_id, semnum, cmd, val) == -1)
    {
      perror("semctl");
      exit(EXIT_FAILURE);
    }
}

int	xsemget(key_t key)
{
  int	sem_id;

  if ((sem_id = semget(key, 1, SHM_R | SHM_W)) == -1)
    {
      if ((sem_id = semget(key, 1, IPC_CREAT | SHM_R | SHM_W)) == -1)
	{
	  perror("semget");
	  exit(EXIT_FAILURE);
	}
      xsemctl(sem_id, 0, SETVAL, 4);
    }
  return (sem_id);
}

int	xshmget(key_t key, int size_map)
{
  int	shm_id;
  int	size;

  size = ((size_map + 1) * sizeof(char *)) + (size_map * (size_map + 1) * sizeof(char));
  if ((shm_id = shmget(key, size, SHM_R | SHM_W)) == -1)
    {
      if ((shm_id = shmget(key, size, IPC_CREAT | SHM_R | SHM_W)) == -1)
	{
	  perror("shmget");
	  exit(EXIT_FAILURE);
	}
    }
  printf("Creating SHM : SHM_ID = %i\n", shm_id);
  return (shm_id);
}

void	delete_ipc(int shm_id)
{
  if (shmctl(shm_id, IPC_RMID, NULL) == -1)
    {
      perror("shmctl");
      exit(EXIT_FAILURE);
    }
}

void	create_map(int shm_id, int size_map)
{
  void	*tmp;
  char	**map;
  int	i;
  int	j;

  i = 0;
  j = 0;
  tmp = shmat(shm_id, NULL, SHM_R | SHM_W);
  map = (char **)tmp;
  while (i < size_map)
    {
      j = 0;
      while (j < size_map)
	{
	  map[i][j] = '*';
	  j++;
	}
      map[i][j] = '\0';
      sprintf((char *)tmp, map[i]);
      i++;
    }
  map[i] = NULL;
  printf("%s\n", map[0]);
} //BUGGER

void	start_game(int size_map)
{
  key_t		key;
  int		shm_id;
  int		sem_id;
  void		*addr;

  key = xftok(xget_current_dir_name(), 0);
  shm_id = xshmget(key, size_map);
  sem_id = xsemget(key);
  create_map(shm_id, size_map);
  delete_ipc(shm_id);
  //  delete_ipc(sem_id);
}

int	main(int ac, char **av)
{
  if (ac == 3 && av[1][0] == '0')
    {
      start_game(atoi(av[2]));
    }
  else if (ac == 3)
    {
      /*      start_play();*/
    }
  else
    printf("Usage: ./lemipc 0 [size_map] || ./lemipc [key] [team]\n");
  return (0);
}
